package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.Menu;
import cn.huhst.cas.weisiqian.service.MenuService;

public class CASFilter implements Filter {

	private Logger logger = Logger.getLogger(CASFilter.class);

	public CASFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		if(session.getAttribute("menulist")==null){
			session.setAttribute("menulist", new MenuService().queryAll());
		}
		String uri = request.getRequestURI();
		uri.replaceAll("\\\\", "/");
		logger.debug("uri:" + uri);
		int start = uri.lastIndexOf('/');
		int end = uri.lastIndexOf('.');
		end = end == -1 ? uri.length() : end;
		String pageName = uri.substring(start + 1, end);
		if (pageName != null && ("index".equals(pageName) || "login".equals(pageName)
				|| "acmintroduction".equals(pageName) || "casintroduction".equals(pageName) || "news".equals(pageName)
				|| "newslist".equals(pageName) || "post".equals(pageName) || "postlist".equals(pageName)
				|| "CheckCode".equals(pageName) || "Login".equals(pageName))) {
			logger.debug("pageName:" + pageName);
			chain.doFilter(request, response);
		} else {
			logger.debug("访问后台页面：" + pageName);
			String logined = (String) session.getAttribute("logined");
			logger.debug("logined=" + logined);
			if (logined == null || !"logined".equals(logined)) {
				logger.debug("用户未登录,重定向到login.html页面");
				request.getRequestDispatcher("login.html").forward(request, response);
			} else {
				String username = (String) session.getAttribute("username");
				logger.debug("用户已登录，登陆用户名：" + username);
				chain.doFilter(request, response);
			}
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
